What is @floating-ui/react-dom?
The @floating-ui/react-dom package is a library for creating floating elements that can be positioned around a target element in a React application. It provides a robust API for positioning tooltips, popovers, dropdowns, and other floating elements, with extensive control over placement, flipping, and shifting based on available space in the viewport.
What are @floating-ui/react-dom's main functionalities?
Positioning Tooltips
This code demonstrates how to create a simple tooltip that appears above a button when clicked. It uses the useFloating hook from @floating-ui/react-dom to manage the tooltip's position and behavior, including automatic adjustment for viewport boundaries.
import { useFloating, offset, flip, shift, arrow } from '@floating-ui/react-dom';
import { useState, useRef } from 'react';
function Tooltip() {
const [open, setOpen] = useState(false);
const arrowRef = useRef(null);
const {x, y, reference, floating, strategy} = useFloating({
placement: 'top',
middleware: [offset(5), flip(), shift({padding: 5}), arrow({element: arrowRef})]
});
return (
<>
<button ref={reference} onClick={() => setOpen(!open)}>
Hover me
</button>
{open && (
<div ref={floating} style={{position: strategy, top: y ?? '', left: x ?? ''}}>
Tooltip content
<div ref={arrowRef} />
</div>
)}
</>
);
}
Creating Popovers
This example shows how to create a popover that appears to the right of a button when clicked. The useFloating hook is used to handle dynamic positioning and flipping to ensure the popover remains visible within the viewport.
import { useFloating, offset, flip, shift } from '@floating-ui/react-dom';
import { useState, useRef } from 'react';
function Popover() {
const [open, setOpen] = useState(false);
const {x, y, reference, floating, strategy} = useFloating({
placement: 'right-start',
middleware: [offset(10), flip(), shift({padding: 8})]
});
return (
<>
<button ref={reference} onClick={() => setOpen(!open)}>
Click me
</button>
{open && (
<div ref={floating} style={{position: strategy, top: y ?? '', left: x ?? ''}}>
Popover content
</div>
)}
</>
);
}
Other packages similar to @floating-ui/react-dom
popper.js
Popper.js is a popular library for managing poppers in web applications. It provides similar functionalities to @floating-ui/react-dom, such as dynamic positioning and flipping of poppers based on the viewport. However, @floating-ui/react-dom is specifically tailored for React and offers a more React-friendly API with hooks.
tippy.js
Tippy.js is another library focused on creating tooltips and popovers. It builds on top of Popper.js and adds an abstraction layer that includes default styling and behavior. Tippy.js is easier to use for simple tooltips and popovers but offers less low-level control compared to @floating-ui/react-dom, which is more configurable and suited for complex positioning scenarios in React applications.